package net.zjitc.servlet.file;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "downloadsServlet", urlPatterns = "/downloadsServlet")
public class DownloadsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取文件名
        String name = request.getParameter("name");
        //先判断此文件是否存在，如果存在才下载
        String path = this.getServletContext().getRealPath("/downloads/"+name);
        File file = new File(path);
        response.setCharacterEncoding("UTF-8");

        if (!file.exists()){
            PrintWriter writer = response.getWriter();
            writer.write("您下载的文件 不存在 ！！");
        }else {
            //通过设置相应头，设置文件下载类型及下载的文件的名称
            response.setHeader("content-disposition","attachment;filename="+name);
            IOUtils.copy(new FileInputStream(file),response.getOutputStream());
        }
    }
}
